package com.gitee.huanminabc.dynamicdb.data;

import com.gitee.huanminabc.dynamicdb.common.Constants;
import com.gitee.huanminabc.dynamicdb.common.DynamicDbException;
import com.gitee.huanminabc.dynamicdb.config.DynamicDbSpringConfig;
import com.gitee.huanminabc.dynamicdb.core.DbKeysManage;
import com.gitee.huanminabc.dynamicdb.core.DynamicDataSourceContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import java.util.HashMap;
import java.util.Map;
/**
 * 文件读取yml里的数据源配置
 * @author huanmin
 * @date 2024/11/22
 */
@Data
@Slf4j
public class YmlDataSourceInitialize implements InitializingBean {
    @Autowired
    private DynamicDbSpringConfig dynamicDbSpringConfig;

    public void initDataSource() {
        log.debug("-----------------YmlDataSourceInitialize------------------");
        Map<String,DataSourceProperties> multiDb = new HashMap<>();
        dynamicDbSpringConfig.getMultiDb().forEach((key, data) -> {
            log.info("[YmlDataSourceInitialize->initDataSource] 注册数据源 key:{}", key);
            DataSourceProperties properties = DynamicDataSourceContext.buildMultiDbDataSource(data);
            multiDb.put(key,properties);
        });

        DynamicDataSourceContext.addDataSource(multiDb);
    }


    @Override
    public void afterPropertiesSet()  {
        //如果默认的数据源为空, 则抛出异常
        if (dynamicDbSpringConfig.getDefaultDbKey() == null) {
            throw new DynamicDbException("默认数据源不能为空");
        }
        //如果开启了多租户模式, 但是没有配置默认租户, 则抛出异常
        if (dynamicDbSpringConfig.isMultiTenantMode() && dynamicDbSpringConfig.getDefaultTenant() == null) {
            throw new DynamicDbException("默认租户不能为空");
        }

        //设置默认的数据源
        Constants.DEFAULT_DB_KEY= dynamicDbSpringConfig.getDefaultDbKey();

        //设置默认的租户
        Constants.DEFAULT_TENANT= dynamicDbSpringConfig.getDefaultTenant();

        //先切换一下, 保证主线程的是默认数据源, 如果是web需要在拦截器中也切换一下
        DbKeysManage.switchDbKey(Constants.DEFAULT_DB_KEY);
        log.info("[YmlDataSourceInitialize->init->init] 默认数据源:{}", dynamicDbSpringConfig.getDefaultDbKey());
        //加载配置文件的数据源
        initDataSource();
    }
}
